/**
 * 
 */
package com.sicent.operate.common.util;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

/**
 * DES加密与解密
 * 
 * @author DSM
 */
public class DESUtils {

	/**
	 * 加密
	 * 
	 * @param encryptString
	 * @return
	 * @throws Exception
	 */
	public static String encryptDES(String encryptString, byte[] iv, String encryptKey) throws Exception {
		IvParameterSpec zeroIv = new IvParameterSpec(iv);
		SecretKeySpec key = new SecretKeySpec(encryptKey.getBytes(), "DES");
		Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
		cipher.init(Cipher.ENCRYPT_MODE, key, zeroIv);
		byte[] encryptedData = cipher.doFinal(encryptString.getBytes());

		return new String(Base64.encode(encryptedData));
	}

	// public static String encryptDESForUrl(String encryptString, byte[] iv,
	// String encryptKey) throws Exception {
	// IvParameterSpec zeroIv = new IvParameterSpec(iv);
	// SecretKeySpec key = new SecretKeySpec(encryptKey.getBytes(), "DES");
	// Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
	// cipher.init(Cipher.ENCRYPT_MODE, key, zeroIv);
	// byte[] encryptedData = cipher.doFinal(encryptString.getBytes());
	//
	// return new String(Base64.encodeForUrl(encryptedData));
	// }

	/**
	 * 解密
	 * 
	 * @param decryptString
	 * @return
	 * @throws Exception
	 */
	public static String decryptDES(String decryptString, byte[] iv, String decryptKey) throws Exception {
		byte[] byteMi = Base64.decode(decryptString.getBytes());
		IvParameterSpec zeroIv = new IvParameterSpec(iv);
		SecretKeySpec key = new SecretKeySpec(decryptKey.getBytes(), "DES");
		Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
		cipher.init(Cipher.DECRYPT_MODE, key, zeroIv);
		byte decryptedData[] = cipher.doFinal(byteMi);

		return new String(decryptedData);
	}

	public static void main(String[] args) throws Exception {
		DESUtils desutils = new DESUtils();
		String a = "abcd&123456";
		String EnString = desutils.encryptDES(a, "salt#&@!".getBytes(), "JS$@!#zh");
		String DeString = desutils.decryptDES(EnString, "salt#&@!".getBytes(), "JS$@!#zh");
		System.out.println(EnString);
		System.out.println(DeString);
	}
}
